import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';

Dio initDio() {
  // 声明 dio 配置项
  BaseOptions _baseOptions = BaseOptions(
    baseUrl: "http://shop.fed.lagounews.com/api",
    connectTimeout: 5000, // 请求服务器的超时时间
  );

  Dio dio = Dio(_baseOptions);

  // 添加拦截器
  dio.interceptors.add(InterceptorsWrapper(
      // 请求拦截
      onRequest: (options, handler) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String token = prefs.getString('token') ?? "";
    int expires_time = prefs.getInt('expires_time') ?? 0;
    int current_time = DateTime.now().millisecondsSinceEpoch ~/ 1000;

    if (token != '' && current_time < expires_time) {
      options.headers['Authorization'] = "Bearer " + token;
    } else {
      options.headers['Authorization'] = "";
    }

    // 请求开始之前，做一些处理
    return handler.next(options); // continue
  },
      // 响应拦截
      onResponse: (response, handler) {
    // 对响应数据进行处理
    return handler.next(response); // continue
  },
      // 报错拦截
      onError: (DioError e, handler) {
    // 对响应报错进行处理
    return handler.next(e); //continue
  }));

  return dio;
}
